package com.djf.djfword.service;

import com.djf.djfword.entity.Employee;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 高级Word文档操作服务类
 * 提供更复杂的Word文档生成功能
 * 
 * @author djf
 */
@Service
public class AdvancedWordService {

    /**
     * 生成员工报告Word文档
     */
    public void generateEmployeeReport(HttpServletResponse response, List<Employee> employees) throws IOException {
        XWPFDocument document = new XWPFDocument();
        
        // 1. 创建文档标题
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("员工信息统计报告");
        titleRun.setBold(true);
        titleRun.setFontSize(20);
        titleRun.setFontFamily("宋体");
        
        // 2. 添加生成日期
        XWPFParagraph dateParagraph = document.createParagraph();
        dateParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFRun dateRun = dateParagraph.createRun();
        dateRun.setText("生成日期：" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
        dateRun.setFontSize(12);
        dateRun.setFontFamily("宋体");
        
        // 3. 添加空行
        document.createParagraph();
        
        // 4. 添加统计信息
        XWPFParagraph statsParagraph = document.createParagraph();
        XWPFRun statsRun = statsParagraph.createRun();
        statsRun.setText("总员工数：" + employees.size() + " 人");
        statsRun.setFontSize(14);
        statsRun.setBold(true);
        statsRun.setFontFamily("宋体");
        
        // 5. 创建员工信息表格
        if (!employees.isEmpty()) {
            document.createParagraph(); // 空行
            
            XWPFTable table = document.createTable();
            
            // 创建表头
            XWPFTableRow headerRow = table.getRow(0);
            String[] headers = {"序号", "姓名", "年龄", "职位", "部门", "薪资", "入职日期", "联系电话"};
            
            for (int i = 0; i < headers.length; i++) {
                if (i == 0) {
                    headerRow.getCell(0).setText(headers[i]);
                } else {
                    headerRow.addNewTableCell().setText(headers[i]);
                }
            }
            
            // 设置表头样式
            for (XWPFTableCell cell : headerRow.getTableCells()) {
                cell.setColor("4472C4");
                XWPFParagraph p = cell.getParagraphs().get(0);
                p.setAlignment(ParagraphAlignment.CENTER);
                XWPFRun run = p.getRuns().get(0);
                run.setBold(true);
                run.setColor("FFFFFF");
                run.setFontFamily("宋体");
                run.setFontSize(11);
            }
            
            // 添加员工数据
            for (int i = 0; i < employees.size(); i++) {
                Employee emp = employees.get(i);
                XWPFTableRow dataRow = table.createRow();
                
                dataRow.getCell(0).setText(String.valueOf(i + 1));
                dataRow.getCell(1).setText(emp.getName());
                dataRow.getCell(2).setText(String.valueOf(emp.getAge()));
                dataRow.getCell(3).setText(emp.getPosition());
                dataRow.getCell(4).setText(emp.getDepartment());
                dataRow.getCell(5).setText(String.format("%.2f", emp.getSalary()));
                dataRow.getCell(6).setText(emp.getHireDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                dataRow.getCell(7).setText(emp.getPhone());
                
                // 设置数据行样式
                for (XWPFTableCell cell : dataRow.getTableCells()) {
                    if (i % 2 == 0) {
                        cell.setColor("F2F2F2");
                    }
                    XWPFParagraph p = cell.getParagraphs().get(0);
                    p.setAlignment(ParagraphAlignment.CENTER);
                    XWPFRun run = p.getRuns().get(0);
                    run.setFontFamily("宋体");
                    run.setFontSize(10);
                }
            }
        }
        
        // 6. 添加统计分析
        document.createParagraph(); // 空行
        
        XWPFParagraph analysisParagraph = document.createParagraph();
        XWPFRun analysisRun = analysisParagraph.createRun();
        analysisRun.setText("统计分析：");
        analysisRun.setBold(true);
        analysisRun.setFontSize(14);
        analysisRun.setFontFamily("宋体");
        
        // 计算平均年龄和平均薪资
        double avgAge = employees.stream().mapToInt(Employee::getAge).average().orElse(0);
        double avgSalary = employees.stream().mapToDouble(Employee::getSalary).average().orElse(0);
        
        XWPFParagraph statsParagraph2 = document.createParagraph();
        XWPFRun statsRun2 = statsParagraph2.createRun();
        statsRun2.setText(String.format("• 平均年龄：%.1f 岁\n• 平均薪资：%.2f 元", avgAge, avgSalary));
        statsRun2.setFontSize(12);
        statsRun2.setFontFamily("宋体");
        
        // 7. 添加页脚
        XWPFParagraph footerParagraph = document.createParagraph();
        footerParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun footerRun = footerParagraph.createRun();
        footerRun.setText("\n\n--- 报告结束 ---");
        footerRun.setFontSize(12);
        footerRun.setFontFamily("宋体");
        footerRun.setItalic(true);
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=employee_report.docx");
        
        // 写入响应流
        document.write(response.getOutputStream());
        document.close();
    }
    
    /**
     * 生成合同模板Word文档
     */
    public void generateContractTemplate(HttpServletResponse response, String employeeName, 
                                       String position, Double salary, LocalDate startDate) throws IOException {
        XWPFDocument document = new XWPFDocument();
        
        // 1. 创建合同标题
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("劳动合同书");
        titleRun.setBold(true);
        titleRun.setFontSize(22);
        titleRun.setFontFamily("宋体");
        
        // 2. 添加空行
        document.createParagraph();
        document.createParagraph();
        
        // 3. 合同编号
        XWPFParagraph contractNoParagraph = document.createParagraph();
        contractNoParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFRun contractNoRun = contractNoParagraph.createRun();
        contractNoRun.setText("合同编号：HT" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "001");
        contractNoRun.setFontSize(12);
        contractNoRun.setFontFamily("宋体");
        
        // 4. 合同正文
        String[] contractContent = {
            "甲方（用人单位）：某某科技有限公司",
            "地址：北京市朝阳区某某街道123号",
            "法定代表人：张某某",
            "",
            "乙方（劳动者）：" + employeeName,
            "身份证号：___________________",
            "联系地址：___________________",
            "",
            "根据《中华人民共和国劳动法》、《中华人民共和国劳动合同法》等法律法规的规定，甲乙双方遵循合法、公平、平等自愿、协商一致、诚实信用的原则，签订本劳动合同。",
            "",
            "第一条 合同期限",
            "本合同为固定期限劳动合同，合同期限自 " + startDate.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")) + " 起至 " + startDate.plusYears(3).format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")) + " 止。",
            "",
            "第二条 工作内容和工作地点",
            "1. 乙方同意根据甲方工作需要，担任 " + position + " 职务。",
            "2. 工作地点：北京市朝阳区某某街道123号",
            "",
            "第三条 劳动报酬",
            "乙方月工资为人民币 " + String.format("%.2f", salary) + " 元，甲方按月支付乙方工资。",
            "",
            "第四条 工作时间和休息休假",
            "甲方安排乙方执行标准工时制，每日工作8小时，每周工作40小时。",
            "",
            "第五条 其他约定",
            "本合同未尽事宜，按国家有关法律法规执行。",
            "",
            "第六条 合同生效",
            "本合同一式两份，甲乙双方各执一份，自双方签字盖章之日起生效。"
        };
        
        for (String content : contractContent) {
            XWPFParagraph paragraph = document.createParagraph();
            if (content.startsWith("第") && content.contains("条")) {
                paragraph.setAlignment(ParagraphAlignment.LEFT);
                XWPFRun run = paragraph.createRun();
                run.setText(content);
                run.setBold(true);
                run.setFontSize(14);
                run.setFontFamily("宋体");
            } else {
                paragraph.setAlignment(ParagraphAlignment.BOTH);
                XWPFRun run = paragraph.createRun();
                run.setText(content);
                run.setFontSize(12);
                run.setFontFamily("宋体");
            }
        }
        
        // 5. 签名区域
        document.createParagraph();
        document.createParagraph();
        
        XWPFParagraph signatureParagraph = document.createParagraph();
        XWPFRun signatureRun = signatureParagraph.createRun();
        signatureRun.setText("甲方（盖章）：_______________    乙方（签字）：_______________\n\n" +
                           "签订日期：" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")) + 
                           "        签订日期：" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
        signatureRun.setFontSize(12);
        signatureRun.setFontFamily("宋体");
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=contract_" + employeeName + ".docx");
        
        // 写入响应流
        document.write(response.getOutputStream());
        document.close();
    }
    
    /**
     * 生成图表样式的Word文档（使用表格模拟图表）
     */
    public void generateChartStyleDocument(HttpServletResponse response) throws IOException {
        XWPFDocument document = new XWPFDocument();
        
        // 标题
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("销售数据分析报告");
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        titleRun.setFontFamily("宋体");
        
        document.createParagraph();
        
        // 创建模拟图表的表格
        XWPFTable chartTable = document.createTable();
        
        // 表头
        XWPFTableRow headerRow = chartTable.getRow(0);
        headerRow.getCell(0).setText("月份");
        headerRow.addNewTableCell().setText("销售额(万元)");
        headerRow.addNewTableCell().setText("增长率(%)");
        headerRow.addNewTableCell().setText("排名");
        
        // 设置表头样式
        for (XWPFTableCell cell : headerRow.getTableCells()) {
            cell.setColor("366092");
            XWPFParagraph p = cell.getParagraphs().get(0);
            p.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun run = p.getRuns().get(0);
            run.setBold(true);
            run.setColor("FFFFFF");
            run.setFontFamily("宋体");
        }
        
        // 模拟数据
        String[][] data = {
            {"1月", "120.5", "15.2", "3"},
            {"2月", "135.8", "12.7", "2"},
            {"3月", "142.3", "4.8", "1"},
            {"4月", "128.9", "-9.4", "4"},
            {"5月", "156.7", "21.5", "1"},
            {"6月", "148.2", "-5.4", "2"}
        };
        
        for (String[] rowData : data) {
            XWPFTableRow dataRow = chartTable.createRow();
            for (int i = 0; i < rowData.length; i++) {
                dataRow.getCell(i).setText(rowData[i]);
                XWPFParagraph p = dataRow.getCell(i).getParagraphs().get(0);
                p.setAlignment(ParagraphAlignment.CENTER);
                XWPFRun run = p.getRuns().get(0);
                run.setFontFamily("宋体");
            }
        }
        
        // 添加分析说明
        document.createParagraph();
        XWPFParagraph analysisParagraph = document.createParagraph();
        XWPFRun analysisRun = analysisParagraph.createRun();
        analysisRun.setText("数据分析：\n" +
                          "1. 5月份销售额最高，达到156.7万元\n" +
                          "2. 整体呈现上升趋势，但4月和6月有所下降\n" +
                          "3. 建议加强4月和6月的营销策略");
        analysisRun.setFontSize(12);
        analysisRun.setFontFamily("宋体");
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=sales_chart_report.docx");
        
        // 写入响应流
        document.write(response.getOutputStream());
        document.close();
    }
}